package com.sunxyz.datasummary.ui;

import com.sunxyz.datasummary.application.DemoService;
import com.sunxyz.datasummary.domain.Demo;
import com.sunxyz.datasummary.domain.DemoRepository;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * Created by yangrd on 2018/6/25
 **/
@RestController
@RequestMapping("/demo")
public class DemoController {

    @Autowired
    private DemoRepository demoRepository;

    @Autowired
    private DemoService demoService;

    @GetMapping
    public Page<Demo> findAll(Pageable pageable){
        return demoRepository.findAll(pageable);
    }


    @PostMapping("import")
    public void save(MultipartFile file){
        try {
            demoService.importExcel(file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/export")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response){
        try {
            download(request,response,"demo.xls", demoService.exportExcel( demoRepository.findAll()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void download(HttpServletRequest request, HttpServletResponse response, String storeName, Workbook book) throws Exception {
        String agent = request.getHeader("USER-AGENT").toLowerCase();
        response.setContentType("application/vnd.ms-excel");
        String fileName = storeName;
        String codedFileName = URLEncoder.encode(fileName, "UTF-8");
        if (agent.contains("firefox")) {
            response.setCharacterEncoding("utf-8");
            response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1"));
        } else {
            response.setHeader("content-disposition", "attachment;filename=" + codedFileName);
        }
        book.write(response.getOutputStream());
    }
}
